<?php
namespace api\modules\v1\models;

use api\components\ApiModel;
use common\models\ARUserCertificate;
use common\models\ARWallet;
use Yii;
use yii\helpers\ArrayHelper;
use common\models\ARAssets;
use api\components\RuleUtil;

/**
 * 信息模型
 * @author WJ
 */
class Wallet extends ApiModel
{
    const SCENARIO_WALLET_LIST = 'wallet_list';
    const SCENARIO_WALLET_BIND = 'wallet_bind';
    const SCENARIO_WALLET_UPDATE = 'wallet_update';
    const SCENARIO_WALLET_DELETE = 'wallet_delete';
    const SCENARIO_WALLET_DEFAULT = 'wallet_default';

    public $wallet_id;
    public $type;
    public $other_type;
    public $bank;
    public $account;
    public $account_name;
    public $describe;
    public $name;
    public $size;
    public $page;

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'wallet_id'    => '收款信息编号',
            'type'         => '账户类型',
            'other_type'   => '其他收款方式',
            'bank'         => '银行',
            'account'      => '账号',
            'account_name' => '账号名称',
            'describe'     => '账号描述',
            'name'         => '账号标签',
            'size'         => '分页大小',
            'page'         => '当前页',
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_WALLET_LIST   => [],
            self::SCENARIO_WALLET_BIND   => ['type', 'other_type', 'bank', 'account'],
            self::SCENARIO_WALLET_UPDATE => ['wallet_id', 'bank', 'account'],
            self::SCENARIO_WALLET_DELETE => ['wallet_id'],
            self::SCENARIO_WALLET_DEFAULT=> ['wallet_id'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['wallet_id', 'type', 'account', 'account_name', 'describe', 'name',
            ], 'trim'],
            [['wallet_id', 'type'], 'required'],
            ['account', 'required', 'on' => self::SCENARIO_WALLET_BIND],
            ['type', 'in', 'range' => [ARWallet::TYPE_BANK, ARWallet::TYPE_ZFB, ARWallet::TYPE_OTHER]],
            ['other_type', 'required', 'when' => function ($model) {
                return $this->type == ARWallet::TYPE_OTHER;
            }],
            ['other_type', 'filter', 'filter' => function ($model) {
                if ($this->type != ARWallet::TYPE_OTHER) {
                    return $this->type ? ARWallet::$type[$this->type] : '';
                }
                return $this->other_type;
            }],
            ['bank', 'required', 'when' => function ($model) {
                return $this->type == ARWallet::TYPE_BANK;
            }],
            ['bank', 'filter', 'filter' => function ($model) {
                if ($this->type != ARWallet::TYPE_BANK) {
                    return null;
                } else {
                    list($flag, $data) = RuleUtil::checkBank($this->bank);
                    if(!$flag){
                        self::throwError(null, $data);
                    }
                }
                return $this->bank;
            }],
            ['size', 'default', 'value' => 10],
            ['page', 'default', 'value' => 1],
            [['size', 'page'], 'integer'],
            [['bank', 'other_type', 'account', 'account_name', 'describe', 'name'], 'string', 'max' => 255],
        ];
    }

    /**
     * 获取钱包安全码
     * @param Object $row 数据记录
     */
    public static function getWalletSecufity($row)
    {
        $salt = Yii::$app->params['salt']['wallet'];
        $param = [
            'uid'          => $row->uid,
            'type'         => $row->type,
            'other_type'   => $row->other_type,
            'account'      => $row->account,
            'account_name' => $row->account_name,
            'describe'     => $row->describe,
            'name'         => $row->name,
        ];
        $addtime = $row->security_at;
        $code = self::getSecurity($param, $addtime, $salt);
        return $code;
    }

    /**
     * 校验资产安全码
     * @param Object $row 数据记录
     */
    public static function verifyWalletSecufity($row)
    {
        $code = self::getWalletSecufity($row);
        if ($code === $row->security_code) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 支付方式简单列表
     */
    public function listPay()
    {
        $data = ARWallet::find()->select(['id', 'other_type', 'account'])->where(['uid' => Yii::$app->user->id, 'is_delete' => ARWallet::DELETE_NOT])->asArray()->all();
        asort($data);
        return $data;
    }

    /**
     * 获取支付方式列表
     */
    public function listWallet()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $sql = ARWallet::find()->where(['uid' => Yii::$app->user->id, 'is_delete' => ARWallet::DELETE_NOT]);
        $count = $sql->count();
        $data = $sql
        // ->limit($this->size)->offset($this->size * ($this->page - 1))
        ->all();
        $row = ArrayHelper::toArray($data, [
            ARWallet::className() => [
                'id',
                'type',
                'other_type',
                'bank' => function($row){
                    list($flag, $data) = RuleUtil::checkBank($row->bank);
                    if($flag){
                        return $data['name'];
                    }else{
                        return ;
                    }
                },
                'account',
                'account_name',
                'security'     => function ($row) {
                    $flag = self::verifyWalletSecufity($row);
                    return ($flag) ? ARWallet::SECURITY_SAFE : ARWallet::SECURITY_UNSAFE;
                },
                'created_time' => function ($row) {
                    return Yii::$app->formatter->asDatetime($row->created_at);
                },
                'updated_time' => function ($row) {
                    return Yii::$app->formatter->asDatetime($row->updated_at);
                },
            ],
        ]);
        return ['count' => $count, 'row' => $row];
    }

    /**
     * 绑定支付方式信息
     */
    public function bindWallet()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $uid = Yii::$app->user->id;
        $is_default = ARWallet::DEFAULT_NOT;
        $count = ARWallet::find()->where(['uid' => $uid])->count();
        if ($count == 0) {
            //第一条支付方式直接设为默认
            $is_default = ARWallet::DEFAULT_IS;
        } else {
            $result = ARWallet::findOne(['uid' => $uid, 'type' => $this->type, 'other_type' => $this->other_type, 'account' => $this->account, 'is_delete' => ARWallet::DELETE_NOT]);
            if ($result) {
                self::throwError('100031');
            }
        }

        $wallet = new ARWallet();
        $wallet->attributes = $this->attributes;
        $wallet->uid = $uid;
        $user_certificate = ARUserCertificate::findOne(['uid' => $uid]);
        $wallet->account_name = ($user_certificate)?$user_certificate->real_name:'';
        $wallet->is_default = $is_default;
        $wallet->is_delete = ARWallet::DELETE_NOT;
        $wallet->security_at = Yii::$app->formatter->asTimeStamp('now');

        $security_code = self::getWalletSecufity($wallet);
        $wallet->security_code = $security_code;
        if (!$wallet->save()) {
            self::getErrorMessge($wallet);
        }
        return ['wallet_id' => $wallet->id];
    }

    /**
     * 更新支付方式信息
     */
    public function updateWallet()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $wallet = ARWallet::findOne(['id' => $this->wallet_id, 'uid' => Yii::$app->user->id, 'is_delete' => ARWallet::DELETE_NOT]);
        if (!$wallet) {
            self::throwError('100032');
        }
        //验证原安全码
        $flag = self::verifyWalletSecufity($wallet);
        if (!$flag) {
            self::throwError('100035');
        }
        $wallet->attributes = array_filter($this->attributes);
        if ($wallet->type != ARWallet::TYPE_BANK) {
            $wallet->bank = null;
        }
        if (!empty($wallet->dirtyAttributes)) {
            $new_wallet = ARWallet::findOne(['type' => $wallet->type, 'other_type' => $wallet->other_type, 'bank' => $wallet->bank, 'account' => $wallet->account, 'is_delete' => ARWallet::DELETE_NOT]);
            if($new_wallet){
                self::throwError('100031');
            }
            $wallet->security_at = Yii::$app->formatter->asTimeStamp('now');

            $security_code = self::getWalletSecufity($wallet);
            $wallet->security_code = $security_code;
            if (!$wallet->update()) {
                self::getErrorMessge($wallet);
            }
        }
        return ['wallet_id' => $wallet->id];
    }

    /**
     * 删除支付方式
     */
    public function deleteWallet()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $wallet = ARWallet::findOne(['id' => $this->wallet_id, 'uid' => Yii::$app->user->id, 'is_delete' => ARWallet::DELETE_NOT]);
        if (!$wallet) {
            self::throwError('100032');
        }
        $tran = Yii::$app->db->beginTransaction();
        try {
            $wallet->is_default = ARWallet::DEFAULT_NOT;
            $wallet->is_delete = ARWallet::DELETE_IS;
            $wallet->update();

            $new_default = ARWallet::findOne(['uid' => Yii::$app->user->id, 'is_delete' => ARWallet::DELETE_NOT]);
            if ($new_default) {
                $new_default->is_default = ARWallet::DEFAULT_IS;
                $new_default->update();
            }
            $tran->commit();
        } catch (\Exception $e) {
            $tran->rollBack();
            throw $e;
        }
        return ['wallet_id' => $wallet->id];
    }

    /**
     * 设置默认支付方式
     */
    public function setDefault()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $wallet = ARWallet::findOne(['id' => $this->wallet_id, 'uid' => Yii::$app->user->id, 'is_delete' => ARWallet::DELETE_NOT]);
        if (!$wallet) {
            self::throwError('100042');
        }

        $default = ARWallet::findOne(['uid' => Yii::$app->user->id, 'is_default' => ARWallet::DEFAULT_IS, 'is_delete' => ARWallet::DELETE_NOT]);
        if ($default && $default->id != $wallet->id) {
            $tran = Yii::$app->db->beginTransaction();
            try {
                $default->is_default = ARWallet::DEFAULT_NOT;
                $default->security_at = Yii::$app->formatter->asTimeStamp('now');
                $security_code = self::getWalletSecufity($default);
                $default->security_code = $security_code;
                $default->update();

                $wallet->is_default = ARWallet::DEFAULT_IS;
                $wallet->security_at = Yii::$app->formatter->asTimeStamp('now');
                $security_code = self::getWalletSecufity($wallet);
                $wallet->security_code = $security_code;
                $wallet->update();
                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        } elseif (!$default) {
            $wallet->is_default = ARWallet::DEFAULT_IS;
            $wallet->security_at = Yii::$app->formatter->asTimeStamp('now');
            $security_code = self::getWalletSecufity($wallet);
            $wallet->security_code = $security_code;
            $wallet->update();
        }
        return ['wallet_id' => $wallet->id];
    }
    
    /**
     * zcy
     * 获取资产余额列表
     */
    public function assestlist()
    {       
        $uid=Yii::$app->user->id;
        $rows=ARAssets::find()->with('coinType')->where(['uid'=>$uid])->all();
        $scale = Yii::$app->params['scale'];
        $rows = ArrayHelper::toArray($rows, [
            ARAssets::className() => [
                'id',
                'uid',
                'coin' => function ($row) {
                    return $row->coinType->name;
                },
                'total_amount' => function ($row) {
                    return bcadd(bcadd($row->amount, $row->amount_freeze,8),$row->amount_vouch,Yii::$app->params['scale']);
                },
                'need_remain_amount' => function ($row){
                    return Need::getNeedAmountInfo($row->coin)['amount_remain_total'];
                },
                'need_trading_amount' => function ($row){
                    return Need::getNeedAmountInfo($row->coin)['amount_trading_total'];
                },
                'amount',
                'amount_vouch'
        
                ],
                ]);
        return $rows;
    }
    
}
